import React, { useState, useEffect } from "react";
import {
  Button,
  Form,
  Input,
  Modal,
  Select,
  Space,
  Switch,
  Table,
  message,
} from "antd";
import styles from "./index.module.scss";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import { NavLink } from "react-router-dom";
import {
  operator_getNews,
  deleteNews,
  batch_delete,
  news_publish,
  news_unpublish,
} from "@/request/api";
import { getFormatTime } from "@/utils";

const { Option } = Select;
const { confirm } = Modal;

export default function NewsConfig() {
  const [dataSource, setDataSource]: any = useState([]);
  const [title, setTitle]: any = useState("");
  const [status, setStatus]: any = useState("");
  // 查询
  const onFinish = (values: any) => {
    const { title, status } = values;
    setTitle(title ? title : "");
    setStatus(status ? status : "");
  };
  useEffect(() => {
    operator_getNews(title).then((res: any) => {
      if (status && status === "published") {
        setDataSource(
          res.news.filter((item: any) => item.status === "published")
        );
      } else if (status && status === "unpublished") {
        setDataSource(
          res.news.filter((item: any) => item.status === "unpublished")
        );
      } else {
        setDataSource(res.news);
      }
    });
  }, [title, status]);
  console.log(dataSource);

  // 是否选中
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [loading, setLoading] = useState(false);
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  const hasSelected = selectedRowKeys.length > 0;
  // 删除选中项
  const handleDelete = () => {
    confirm({
      title: "你确定要删除吗？",
      icon: <ExclamationCircleOutlined />,
      onOk() {
        setLoading(true);
        setTimeout(() => {
          batch_delete({ ids: selectedRowKeys.join(",") });
          setDataSource(
            dataSource.filter((data: any) => !selectedRowKeys.includes(data.id))
          );
          dataSource.filter((data: any) => !selectedRowKeys.includes(data.id));
          message.info(`删除成功`);
          setSelectedRowKeys([]);
          setLoading(false);
        }, 1000);
      },
      onCancel() {
        console.log("取消");
      },
    });
  };
  // 删除
  const confirmMethod = (item: any) => {
    confirm({
      title: "你确定要删除吗？",
      icon: <ExclamationCircleOutlined />,
      onOk() {
        console.log("ok");
        deleteMethod(item);
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  };
  const deleteMethod = (item: any) => {
    setDataSource(dataSource.filter((data: any) => data.id !== item.id));
    deleteNews(item.id);
  };
  // 表格
  const columns = [
    {
      title: "封面",
      dataIndex: "cover",
      render: (cover: any) => {
        return cover ? (
          <img
            style={{ width: "80px" }}
            src={`http://10.106.8.197:9000/lanmei/${cover}`}
          />
        ) : (
          "无封面"
        );
      },
    },
    {
      title: "新闻标题",
      dataIndex: "title",
    },
    {
      title: "可见性",
      dataIndex: "status",
      render: (status: any, item: any) => {
        return (
          <Switch
            checked={status === "published"}
            disabled={item.default}
            onChange={() => {
              handleChange(item);
            }}
          ></Switch>
        );
      },
    },
    {
      title: "创建时间",
      dataIndex: "created_at",
      render: (created_at: any) => {
        return getFormatTime(created_at);
      },
    },
    {
      title: "操作",
      render: (item: any) => {
        return (
          <div>
            <Button
              type="link"
              onClick={() => {
                location.href = `newsConfig/newsUpdate/${item.id}`;
              }}
            >
              编辑
            </Button>
            <Button type="link" danger onClick={() => confirmMethod(item)}>
              删除
            </Button>
          </div>
        );
      },
    },
  ];
  // 是否可见
  const handleChange = (item: any) => {
    item.status = item.status === "published" ? 0 : "published";
    setDataSource([...dataSource]);
    let itemId = item.id;
    item.status === "published"
      ? news_publish({ ids: itemId.toString() })
      : news_unpublish({ ids: itemId.toString() });
  };

  return (
    <div
      style={{
        backgroundColor: "#c1e1fd",
        minHeight: "100vh",
      }}
    >
      <div className={styles.topSearch}>
        <Form
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{}}
          onFinish={onFinish}
        >
          <Space direction="horizontal" size={90}>
            <Form.Item
              label="新闻标题"
              name="title"
              style={{ marginBottom: 0 }}
              labelCol={{ span: 15 }}
            >
              <Input style={{ width: 160, border: "1px solid white" }} />
            </Form.Item>

            <Form.Item
              label="可见性"
              name="status"
              style={{ marginBottom: 0 }}
              labelCol={{ span: 15 }}
            >
              <Select style={{ width: 160 }}>
                <Option value="全部">全部</Option>
                <Option value={"published"}>可见</Option>
                <Option value={"unpublished"}>不可见</Option>
              </Select>
            </Form.Item>

            <Space style={{ marginBottom: 0 }}>
              <Button
                type="default"
                htmlType="reset"
                style={{
                  marginLeft: 50,
                }}
              >
                重置
              </Button>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </Space>
          </Space>
        </Form>
      </div>

      <Space style={{ margin: "0 25px" }}>
        <NavLink to={"addNew"}>
          <Button type="primary">添加新闻</Button>
        </NavLink>
        <Button
          type="primary"
          danger
          onClick={handleDelete}
          disabled={!hasSelected}
          loading={loading}
        >
          批量删除
        </Button>
      </Space>

      <Table
        rowSelection={rowSelection}
        dataSource={dataSource}
        columns={columns}
        pagination={{
          pageSize: 6,
        }}
        rowKey={(item) => item.id}
        style={{ margin: "25px" }}
      />
    </div>
  );
}
